package com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.util

import android.app.Application
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerStateListener
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.AESCryptUtil
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.apiHostCommonCombine
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.createApiAction
import com.helasasa.maxfunds.lineofcredit.cashloan.utils.analytics.http.HttpHelper
import com.google.gson.Gson

object GoogleInstallUtil {

    /**
     * google play 返回的install referrer，
     * 建议每个接口都需要带上这个字段
     */
    private var mInstallReferrer: String = ""

    /** 句柄 */
    private var mInstallReferrerClient: InstallReferrerClient =
        InstallReferrerClient.newBuilder(ProjectApplication.instance).build()

    /**
     * 初始化google install referref模块
     *
     * @param context Application
     */
    fun init(context: Application) {
        init(context) {
            saveS2sInfo()
        }
    }

    /**
     * 初始化google install referref模块
     *
     * @param context Application
     * @param success 成功回调
     */
    fun init(context: Application, success: (String) -> Unit) {
        try {
            if (mInstallReferrer.isBlank()) {
                mInstallReferrerClient.startConnection(object :
                    InstallReferrerStateListener {
                    override fun onInstallReferrerSetupFinished(responseCode: Int) {
                        when (responseCode) {
                            InstallReferrerClient.InstallReferrerResponse.OK -> {
                                try {
                                    val response = mInstallReferrerClient.installReferrer
                                    mInstallReferrer = response?.installReferrer ?: ""
                                    mInstallReferrerClient.endConnection()

                                    //回调通知
                                    success.invoke(getInstallReferrer())

                                } catch (e: Exception) {
                                    e.printStackTrace()
                                    mInstallReferrerClient.endConnection()
                                }
                            }

                            InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {

                                println("FEATURE_NOT_SUPPORTED")
                                mInstallReferrerClient.endConnection()
                            }

                            InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE -> {

                                println("SERVICE_UNAVAILABLE")
                                mInstallReferrerClient.endConnection()
                            }
                        }
                    }

                    override fun onInstallReferrerServiceDisconnected() {
                    }
                })
            } else {
                //回调通知
                success.invoke(getInstallReferrer())
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 获取Install Referrer
     */
    fun getInstallReferrer(): String {
        return mInstallReferrer
    }

    /**
     * 保存google s2s信息
     */
    fun saveS2sInfo() {
        val params = HashMap<String, Any>().createApiAction().apply {
            put("path", "K6yCW6dykwHZ5xslvQzcSA")
            put("channelCode", getInstallReferrer())
            put("subChannelCode", getInstallReferrer())
            put("sourceType", "google")
        }
        val content = Gson().toJson(params).trim()
        println("aes before：\n $content")
        // 加密后
        val body: String = AESCryptUtil.encryptDefault(content)
        println("aes after：\n $body")
        HttpHelper.postData(apiHostCommonCombine(), body)
    }
}